var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../services/user.js');
var WxParse = require('../../lib/wxParse/wxParse.js');
var app = getApp();

Page({
  data: {
    id: 0,
    userInfo: {},
    user_id: 0,
    chooseSize: false,
    animationData: {},
    //排行
    rankNum: 0,
    //已经邀请的人数
    inviterCount: 0,
    needCount: 0,
    //我的助力人
    inviter_info: {},
    address: '',
    isGetCoupon: false,
    imgInfo: {},
    getCouponCount: 0,
    copytext: '',
    maxtime: 0,
    isHiddenLoading: true,
    isHiddenToast: true,
    dataList: {},
    countDownDay: 0,
    countDownHour: 0,
    countDownMinute: 0,
    countDownSecond: 0,
    //弹窗选择
    openSelectRegion: false,
    regionType: 1,
    canvasHidden: true, //设置画板的显示与隐藏，画板不隐藏会影响页面正常显示
    //redHidden: true,
    shareImgPath: '',
    screenWidth: '', //设备屏幕宽度
    description: '123456789', //奖品描述
    FilePath: '', //头像路径
    user_id: 0,
    imgUrl: '',
    posterImg: '',

    // 自定义弹窗
    showModal: false,
    buttonText: '确认',
    modalContent: '',
    modalContentLast: '',
    action: '',
    helpName: '',
    couponImg: '',
    showModalImg: false,
    modalContentImg: '',
    buttonTextImg: '点击领取',
    actionImg: '',
    couponNum: 0,
    opentype: false,
  },

  //   下拉刷新
  onPullDownRefresh() {
    this.onShow();
    wx.stopPullDownRefresh();
  },
  onLoad: function(options) { // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    console.log('options.id值 ' + options.id)
    console.log('user_id值 ' + wx.getStorageSync('user_id'))

    // 判断是否存在user_id，存在则是邀请，不存在，则是自动进入的
    if (options.id || options.scene) {
      //不能自己给自己助力
      if (options.id == wx.getStorageSync('user_id')) {
        return;
      }
      if (options.id) {
        that.setData({
          id: options.id
        });
      }
      if (options.scene) {
        that.setData({
          id: options.scene
        });
      }

      //进行请求操作，对用户数据操作
      wx.request({
        url: api.getInviterUserInfo,
        data: {
          id: that.data.id,
          user_id: wx.getStorageSync('user_id')
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "POST",
        success: function(res) {
          console.log('3' + res.data);

          if (res.data.is_inviter == false) {

            that.setData({
              showModal: true,
              modalContent: '您已经为该好友助力过了',
              buttonText: '我要参加',
              action: 'helpSuccess',
            })
            // wx.showModal({
            //   title: '温馨提示',
            //   content: '您已经为该好友助力过啦',
            //   showCancel: false,
            //   confirmText: '我要参加',
            //   success: function(res) {
            //     wx.navigateTo({
            //       url: '/pages/share/share',
            //     })
            //   }
            // });
          }
          // else if (res.data.result.count == 6) {
          //   wx.showModal({
          //     title: '温馨提示',
          //     content: '你要助力的好友已经满足条件啦',
          //     showCancel: false,
          //     confirmText: '我要参加',
          //     success: function(res) {
          //       wx.navigateTo({
          //         url: '/pages/share/share',
          //       })
          //     }
          //   });
          // } 
          else {
            let userInfo = wx.getStorageSync('userInfo');
            that.setData({
              showModal: true,
              modalContent: '你正在为',
              helpName: res.data.result.nickname,
              modalContentLast: '助力拼团',
              buttonText: '点击助力',
              action: 'help',
              opentype: userInfo ? false : true
            })
            // wx.showModal({
            //   title: '你正在为' + res.data.result.nickname + '助力拼团',
            //   content: '你正在为' + res.data.result.nickname + '助力拼团',
            //   confirmText: '点击助力',
            //   showCancel: false,
            //   //成功则插入记录
            //   success: function(res) {
            //     let userInfo = wx.getStorageSync('userInfo');
            //     let token = wx.getStorageSync('token');
            //     let user_id = wx.getStorageSync('user_id');
            //     if (userInfo && token) {
            //       wx.request({
            //         url: api.addInviter,
            //         data: {
            //           id: that.data.id,
            //           userInfo: JSON.stringify(userInfo),
            //           user_id: user_id,
            //         },
            //         header: {
            //           "Content-Type": "application/x-www-form-urlencoded",
            //         },
            //         method: "POST",
            //         success: function(res) {
            //           wx.showToast({
            //             title: '助力成功',
            //           });
            //           //助力成功跳转
            //           // wx.navigateTo({
            //           //   url: '/pages/cheerResult/cheerResult',
            //           // });
            //         }
            //       })
            //     } else {
            //       wx.navigateTo({
            //         url: '/pages/ucenter/auth/auth?id=' + that.data.id,
            //       });
            //     }

            //   }
            // })
          }
        }
      });
    } else {

    }

    //点击分享到朋友圈
    wx.showShareMenu({
      withShareTicket: true,
      success: function(res) {
        console.log('分享操作初始化成功');
        console.log(res);
      },
      fail: function(res) {
        console.log(res);
      }
    });

    console.log('授权用户信息' + that.data.userInfo);
  },

  /* 分享页面 */
  onShareAppMessage: function(res) {
    if (res.from === 'button') {
      console.log(res.target);
    }
    var that = this;
    return {
      title: '思瑞送你一份免费变美的机会，只需好友助力，即可变美',
      path: '/pages/share/share?id=' + app.globalData.user_id,
      imageUrl: 'https://shop.nnsirui.com/statics/images/wxshop/bg_01.jpg',
      success: function(res) {
        console.log('转发成功');

      },
      fail: function(res) {
        console.log('转发失败')
      }
    }
  },

  getPhoneNumber: function(e) {
    console.log('iv的值' + e.detail.iv);
    console.log('encryptedData的值' + e.detail.encryptedData);
    wx.login({
      success: res => {
        console.log('code的值' + res.code);
        // wx.request({
        //   url: api.getPhoneNumber,
        //   data: {
        //     'encryptedData': encodeURIComponent(e.detail.encryptedData),
        //     'iv': e.detail.iv,
        //     'code': res.code
        //   },
        //   method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        //   header: {
        //     'content-type': 'application/x-www-form-urlencoded'
        //   }, // 设置请求的 header
        //   success: function (res) {
        //     if (res.data.status == 1) {//我后台设置的返回值为1是正确
        //       //存入缓存即可
        //       //wx.setStorageSync('phone', res.phone);

        //       console.log(res.data.result);
        //     }
        //   },
        //   fail: function (err) {
        //     console.log(err);
        //   }
        // })
      }
    })
  },

  bindGetUserInfo(e) {
    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');
    if (userInfo && token) {
      return;
    }
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      user.loginByWeixinxxc(e.detail).then(res => {
        this.setData({
          userInfo: res.userInfo,
          inviter_info: res.inviter_info
        });
        app.globalData.userInfo = res.userInfo;
        app.globalData.inviter_info = res.inviter_info;
        app.globalData.token = res.token;
        this.onShow();
      }).catch((err) => {
        console.log(err)
      });
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '提示',
        content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
        success: function(res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                if (res.authSetting["scope.userInfo"]) { ////如果用户重新同意了授权登录
                  user.loginByWeixinxxc(e.detail).then(res => {
                    this.setData({
                      userInfo: res.data.userInfo,
                      inviter_info: res.inviter_info
                    });
                    this.onShow();
                    app.globalData.userInfo = res.data.userInfo;
                    app.globalData.token = res.data.token;
                    app.globalData.inviter_info = res.inviter_info;
                  }).catch((err) => {
                    console.log(err)
                  });
                }
              }
            })
          }
        }
      });
    }
  },

  onReady: function() {
    var that = this;
    var time = that.data.maxtime
    // 页面渲染完成
    var totalSecond = 1541951999 - Date.parse(new Date()) / 1000;
    //var totalSecond = time - Date.parse(new Date()) / 1000;

    var interval = setInterval(function() {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        // wx.showToast({
        //   title: '活动已结束',
        // });
        this.setData({
          countDownDay: '0',
          countDownHour: '0',
          countDownMinute: '0',
          countDownSecond: '0',
        });
      }
    }.bind(this), 1000);

    //获取用户设备信息，屏幕宽度
    wx.getSystemInfo({
      success: res => {
        that.setData({
          screenWidth: res.screenWidth
        })
        console.log(that.data.screenWidth)
      }
    });
  },
  onShow: function() {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let inviter_info = wx.getStorageSync('inviter_info');
    let token = wx.getStorageSync('token');
    let user_id = wx.getStorageSync('user_id');
    // 页面显示
    if (userInfo && token) {
      app.globalData.userInfo = userInfo;
      app.globalData.token = token;
      app.globalData.user_id = user_id;
      app.globalData.inviter_info = inviter_info;

      //获取携带用户id的小程序二维码
      wx.request({
        url: api.getQrCode,
        data: {
          user_id: user_id,
        },
        header: {
          'content-type': 'application/json',
        },
        //responseType: 'arraybuffer',
        method: "GET",
        success: function(res) {
          console.log(res);
          // that.setData({
          //   imgUrl: res.data.result
          // });
          wx.downloadFile({
            url: res.data.result,
            success: function(res) {
              console.log("小程序" + res.tempFilePath);
              that.setData({
                imgUrl: res.tempFilePath,
              })
            }
          });
          wx.downloadFile({
            url: "https://shop.nnsirui.com/statics/images/wxshop/poster.jpg",
            success: function(res) {
              console.log("海报" + res.tempFilePath);
              that.setData({
                posterImg: res.tempFilePath,
              })
            }
          })
        }
      })
    }

    this.setData({
      userInfo: userInfo,
      user_id: user_id,
      inviter_info: inviter_info
    });

    console.log('12345' + wx.getStorageSync('inviter_info'));
    // 我的排行

    // 判断是否已经邀请6个人，是领取折扣，否，邀请了多少人

    if (userInfo && token) {
      wx.request({
        url: api.myInviterInfo,
        data: {
          id: that.data.user_id,
        },
        header: {
          "content-type": "application/x-www-form-urlencoded",
        },
        method: 'POST',
        success: function(res) {
          console.log(res);
          //获取数据成功之后 ，显示信息
          that.setData({
            inviterCount: res.data.result.count,
            needCount: res.data.result.need_count,
            rankNum: res.data.result.user_id,
            address: res.data.result.address,
            isGetCoupon: res.data.result.isGetCoupon,
            inviter_info: res.data.inviter_info
          });
          console.log('isGetCoupon的值为' + that.data.isGetCoupon)
        },
      });
    }
    wx.request({
      url: api.getInitInfo,
      header: {
        "content-type": "application/json",
      },
      method: 'GET',
      success: function(res) {
        console.log(res);
        //获取数据成功之后 ，显示信息
        that.setData({
          imgInfo: res.data.imgInfo,
          maxtime: res.data.time,
          getCouponCount: res.data.count,
          copytext: (res.data.copytext.length > 42) ? res.data.copytext.substring(0, 42)+'...' : res.data.copytext
        });

        WxParse.wxParse('activeDetail', 'html', res.data.imgInfo.detail_img, that, 0);
      }
    });
  },
  // 小程序启动自动更新处理
  onLauch: function () {
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭

  },

  //领取打折券
  getCoupon: function(e) {
    var that = this;
    wx.request({
      url: api.getCoupon,
      data: {
        user_id: that.data.user_id,
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      method: 'POST',
      success: function(res) {
        var path = res.data.path;
        if (res.data.status === 1) {
          that.setData({
            showModalImg: true,
            modalContentImg: res.data.discount,
            couponNum: res.data.coupon_num,
            buttonTextImg: '点击领取',
            couponImg: '/static/images/red_img.png',
            actionImg: 'getCouponSuccess',
          });

          // wx.showModal({
          //   title: res.data.msg,
          //   content: res.data.content,
          //   showCancel: false,
          //   confirmText: '确认领取',
          //   success: function(res) {
          //     wx.showToast({
          //       title: '领取成功',
          //     });
          //     wx.navigateTo({
          //       url: path,
          //     });
          //   }
          // });
        } else {
          that.setData({
            showModal: true,
            modalContent: res.data.err,
            buttonText: '确定',
            action: 'getCouponErr',
          });

          // wx.showModal({
          //   title: res.data.err,
          //   content: res.data.msg,
          //   showCancel: false,
          //   confirmText: '确定',
          //   success: function(res) {
          //     wx.switchTab({
          //       url: path,
          //     });
          //   }
          // })
        }
      }
    });
  },

  // 跳转到小程序个人中心
  wxShop: function() {
    var that = this
    //判断该用户是否已经绑定了手机号码，未绑定则先进行绑定再跳转到个人中心
    var userInfo = wx.getStorageSync('userInfo');
    var token = wx.getStorageSync('token');

    if (userInfo && token) {
      wx.request({
        url: api.verifyUsername,
        data: {
          username: userInfo.userName
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: "POST",
        success: function(res) {
          if (res.data.status === 1) {
            wx.switchTab({
              url: '/pages/ucenter/index/index',
            });
          } else {
            that.setData({
              showModal: true,
              modalContent: '请先绑定手机号码',
              buttonText: '确定',
              action: 'bindMobile',
            });
            // wx.showModal({
            //   title: '请先绑定手机号码',
            //   success: function(res) {
            //     wx.navigateTo({
            //       url: '/pages/ucenter/mobile/mobile',
            //     });
            //   },
            //   showCancel: false,
            // })
          }
        }
      })
    } else {
      wx.switchTab({
        url: '/pages/ucenter/index/index',
      });
    }
  },

  //弹窗操作
  cancelSelectRegion() {
    this.setData({
      openSelectRegion: false,
      regionType: this.data.regionDoneStatus ? 3 : 1
    });

  },

  chooseRegion() {
    let that = this;
    this.setData({
      openSelectRegion: !this.data.openSelectRegion
    });
  },

  goTop() {
    wx.navigateTo({
      url: '/pages/top/top',
    })
  },

  //定义的保存图片方法
  saveImageToPhotosAlbum: function() {
    wx.showLoading({
      title: '保存中...',
    })
    var that = this;
    //设置画板显示，才能开始绘图
    that.setData({
      canvasHidden: false
    })
    var unit = that.data.screenWidth / 375
    var path1 = that.data.posterImg
    console.log('二维码地址' + that.data.imgUrl)
    console.log('海报地址' + that.data.posterImg)

    var path2 = that.data.imgUrl
    var context = wx.createCanvasContext('share')
    var description = that.data.description
    // var wxappName = "来「 " + that.data.wxappName + " 」试试运气"
    context.drawImage(path1, 0, 0, unit * 375, unit * 670)
    //   context.drawImage(path4, unit * 164, unit * 40, unit * 48, unit * 48)
    context.drawImage(path2, unit * 125, unit * 400, unit * 145, unit * 135)
    //context.drawImage(path2, unit * 120, unit * 400, unit * 200, unit * 200)
    //   context.drawImage(path4, 48, 200, 280, 128)
    context.setFontSize(14)
    context.setFillStyle("#999")
    // context.fillText("长按识别小程序", unit * 90, unit * 408)
    // context.fillText(wxappName, unit * 90, unit * 428)
    //把画板内容绘制成图片，并回调 画板图片路径
    context.draw(false, function() {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: unit * 375,
        height: unit * 670,
        destWidth: unit * 375,
        destHeight: unit * 670,
        canvasId: 'share',
        success: function(res) {
          that.setData({
            shareImgPath: res.tempFilePath
          })
          if (!res.tempFilePath) {
            wx.showModal({
              title: '提示',
              content: '图片绘制中，请稍后重试',
              showCancel: false
            })
          }

          //图片预览
          // console.log('朋友圈分享图生成成功:' + res.tempFilePath)
          // wx.previewImage({
          //   current: res.tempFilePath, // 当前显示图片的http链接
          //   urls: [res.tempFilePath] // 需要预览的图片http链接列表
          // })

          console.log(that.data.shareImgPath)
          //画板路径保存成功后，调用方法吧图片保存到用户相册
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            //保存成功失败之后，都要隐藏画板，否则影响界面显示。
            success: (res) => {
              console.log(res)
              wx.hideLoading()
              
              that.setData({
                showModal: true,
                modalContent: that.data.copytext,
                buttonText: '一键复制文字，去发朋友圈',
                action: 'copytext',
              })
              
              that.setData({
                canvasHidden: true
              })
            },
            fail: (err) => {
              console.log(err)
              wx.hideLoading()
              that.setData({
                canvasHidden: true
              })
            }
          })
        }
      })
    });
  },

  submit: function() {
    var that = this;
    that.setData({
      showModalImg: true,
      modalContentImg: '0.55',
      buttonTextImg: '点击领取',
      couponImg: '/static/images/red_img.png',
      actionImg: 'getCouponSuccess',
    });
  },

  preventTouchMove: function() {

  },

  go: function() {
    this.setData({
      showModal: false
    })
  },
  close: function() {
    this.setData({
      showModal: false
    })

    this.onShow();
  },

  help: function() {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');
    let user_id = wx.getStorageSync('user_id');
    if (userInfo && token) {
      wx.request({
        url: api.addInviter,
        data: {
          id: that.data.id,
          userInfo: JSON.stringify(userInfo),
          user_id: user_id,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "POST",
        success: function(res) {
          wx.showToast({
            title: '助力成功',
          });
          that.setData({
            showModal: false,
          });
          
        }
      })
    } else {
      // wx.navigateTo({
      //   url: '/pages/ucenter/auth/auth?id=' + that.data.id,
      // });
    }
  },

  bindUserInfo(e) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');
    let user_id = wx.getStorageSync('user_id');
    if (userInfo && token) {
      return;
    }
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      user.loginByWeixinxxc(e.detail).then(res => {
        this.setData({
          userInfo: res.userInfo,
          inviter_info: res.inviter_info
        });
        app.globalData.userInfo = res.userInfo;
        app.globalData.inviter_info = res.inviter_info;
        app.globalData.token = res.token;

        wx.request({
          url: api.getInviterUserInfo,
          data: {
            id: that.data.id,
            user_id: wx.getStorageSync('user_id')
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          method: "POST",
          success: function(res) {
            console.log('3' + res.data);

            if (res.data.is_inviter == false) {
              that.setData({
                showModal: true,
                modalContent: '您已经为该好友助力过了',
                helpName: '',
                modalContentLast: '',
                buttonText: '我要参加',
                opentype: false,
                action: 'authshow',
              })

              // wx.showModal({
              //   title: '温馨提示',
              //   content: '您已经为该好友助力过了',
              //   showCancel: false,
              //   confirmText: '我要参加',
              //   success: function (res) {
              //     wx.navigateTo({
              //       url: '/pages/share/share',
              //     })
              //   }
              // });
            } else {
              wx.request({
                url: api.addInviter,
                data: {
                  id: that.data.id,
                  userInfo: JSON.stringify(that.data.userInfo),
                  user_id: that.data.user_id,
                },
                header: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
                method: "POST",
                success: function(res) {
                  if (res.data.status === 1) {
                    that.setData({
                      showModal: false,
                    });
                    wx.showToast({
                      title: '助力成功',
                    });
                  }
                }
              })
            }
          }
        });

      }).catch((err) => {
        console.log(err)
      });
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告通知',
        content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
        success: function(res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                if (res.authSetting["scope.userInfo"]) { ////如果用户重新同意了授权登录
                  user.loginByWeixin(e.detail).then(res => {
                    this.setData({
                      userInfo: res.userInfo,
                      inviter_info: res.inviter_info
                    });
                    app.globalData.userInfo = res.userInfo;
                    app.globalData.inviter_info = res.inviter_info;
                    app.globalData.token = res.token;
                    this.onShow();
                  }).catch((err) => {
                    console.log(err)
                  });
                }
              }
            })
          }
        }
      });
    }
  },

  helpSuccess: function() {
    var that = this;
    that.setData({
      showModal: false,
    })
  },

  bindMobile: function() {
    wx.navigateTo({
      url: '/pages/ucenter/mobile/mobile',
    });
  },

  getCouponSuccess: function() {
    var that = this;
    wx.showToast({
      title: '领取成功',
      icon: 'succ',
      success: function() {
        var that = this;
        that.setData({
          showModalImg: false,
        })
      }
    });
  },

  getCouponErr: function() {
    var that = this;
    that.setData({
      showModal: false,
    })
  },

  authshow: function() {
    var that = this;
    that.setData({
      showModal: false,
    })
    // wx.navigateTo({
    //   url: '/pages/share/share',
    // })
  },

  copytext: function (){
    var that = this;

    wx.setClipboardData({
      data: that.data.copytext,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 3000,
          success: function () {
            that.setData({
              showModal:false,
            })
          }
        });
      }
    })
  },
});